<template>
  <div>
    <el-tabs v-loading="monitor.loading" type="border-card" class="store-tabs" @tab-click="onTabClick"
       v-model="paneActiveName">
      <!-- 监控选项 -->
      <el-tab-pane class="monitor-tab-pane" label="监控" name="monitor">
        <el-row :gutter="20">
          <!-- 单个数据列表 -->
          <el-col class="lg-mb-20" :xs="24" :sm="12" :md="12" :lg="12">
            <el-card shadow="always" header="状态参数">
              <el-table class="paramsTable" ref="multipleTableRef" :data="monitor.tableData" style="width: 100%"
                @selection-change="handleSelectionChange" :show-header="false">
                <el-table-column type="selection" width="40" />
                <el-table-column prop="icon" width="45">
                  <template #default="scope">
                    <Icon size="15" :name="scope.row.icon" />
                  </template>
                </el-table-column>
                <el-table-column prop="parameter" label="参数" width="200" />
                <el-table-column prop="current_value" label="当前值">
                  <template #default="scope">
                    {{ scope.row.parameter == '换炭以后环保设备运行时长'
                    ?(monitor.itemData[scope.row.current_value as keyof typeof keys]/3600).toFixed(2)
                    :scope.row.parameter == '环保设备总运行时长' 
                    ?(monitor.itemData[scope.row.current_value as keyof typeof keys]/3600).toFixed(2)
                    :monitor.itemData[scope.row.current_value as keyof typeof keys] }}
                    <span>{{
                      scope.row.parameter == '风速流量' ? ' m/s' : scope.row.parameter == '温度' ? `
                                          &#8451` : scope.row.parameter == '环保设备总运行时长' ? ' 时' : scope.row.parameter ==
                        '电流' ? ' A' : scope.row.parameter == '电压' ? ' V' : scope.row.parameter == '电频' ? ' HZ'
                          : scope.row.parameter == '换炭以后环保设备运行时长' ? ' 时' : ' pa'
                    }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column prop="type">
                  <template #default="scope">
                    <component v-if="scope.row.type !== 'thisTime'" is="DataLine" @click="showEcharts(scope.row.type)"
                      style=" width: 1.3em; height: 1.3em;color: green; cursor: pointer; ">
                    </component>
                    <span v-else></span>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-col>
          <!-- 折线图表 -->
          <el-col class="lg-mb-20" :xs="24" :sm="12" :md="12" :lg="12">
            <el-card shadow="always" header="图示" v-loading="baseConfig.loading">
              <template #header>
                <div class="card-header" style="display: flex;">
                  <!-- <el-date-picker v-model="stateTime" range-separator="To" start-placeholder="开始时间"
                    end-placeholder="截至时间" size="default" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                    type="datetimerange" :picker-options="{
                      disabledDate: (time:any) => {
            return time.getTime() > Date.now()
          }
                    }" ></el-date-picker> -->
                  <el-date-picker v-model="stateTime" :disabled-date="pickerOptions" type="datetimerange"
                    range-separator="-" start-placeholder="开始时间" end-placeholder="截止时间"
                    value-format="YYYY-MM-DD HH:mm:ss" style="width:300px" @change="timeChange"></el-date-picker>
                </div>
              </template>
              <div ref="deviceEchartRef" class="showEchart" ></div>
            </el-card>
          </el-col>
          <!-- 坐标日历图 -->
          <el-col class="lg-mb-20" :xs="24" :sm="24" :md="24" :lg="24">
            <el-card v-loading="baseConfig.calendarLoading" shadow="always" header="环保设备总运行时长/日历图">
              <el-collapse v-model="historyName">
                <el-collapse-item title="运行时长" name="1">
                  <template #title>
                    <el-icon>
                      <Timer />
                    </el-icon>
                   更新日历图：选择时间<span style="color: red;">--></span>点击 <component  is="DataLine"
                      style=" width: 1.3em; height: 1.3em;color: green; cursor: pointer; "></component>按钮释放组件<span style="color: red;">--></span>再次点击<component  is="DataLine"
                      style=" width: 1.3em; height: 1.3em;color: green; cursor: pointer; "></component>更新数据<span  style="font-size:2rem;color: burlywood;">/</span>当前数据时间:{{ stateTime[0]?stateTime[0]:defaultTime.yesterday }} 至 {{stateTime[1]?stateTime[1]:defaultTime.today}}
                  </template>
                  <div class="historyWork" ref="historyWorkChartRef"></div>
                </el-collapse-item>
              </el-collapse>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
      <!-- 事件选项 -->
      <el-tab-pane v-if="operatorShowOff([route.path + '/edit'])" class="event-tab-pane" label="事件" :lazy="true" name="event" >
        <el-row :gutter="20">
          <!-- 事件散点图 -->
          <el-col class="lg-mb-20" :xs="24" :sm="24" :md="24" :lg="24">
            <el-card shadow="always" header="事件概览">
              <div ref="eventEchartsRef" class="eventEchart"></div>
            </el-card>
          </el-col>
          <el-col class="lg-mb-20" :xs="24" :sm="24" :md="24" :lg="24">
            <el-card shadow="always" header="事件列表">
              <Event v-if="eventIsShow" />
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane :lazy="true" class="basic-tab-pane" label="基本信息" name="baseInfo">
        <BasicInfo :base-info="monitor.deviceData"  />
      </el-tab-pane>
      <el-tab-pane :lazy="true" class="history-tab-pane" label="历史数据" name="history">
        <History v-if="historyPart.show" />
      </el-tab-pane>
    </el-tabs>
    <!-- 表单 -->
    <PopupForm v-model="baseConfig.showForm" />
  </div>
</template>
<script lang="ts" setup>
import {
  reactive,
  ref,
  onMounted,
  onActivated,
  watch,
  onBeforeMount,
  onBeforeUnmount,
  nextTick,
  inject
} from "vue";
import type baTableClass from "@/utils/baTable";
import { useRoute } from "vue-router";
import { useBackendMonitor } from "@/store/backend/EquipM/monitor";
import { time } from "@/utils/time";
import PopupForm from "../popupForm.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import BasicInfo from "./basicInfo.vue";
import Event from "./eventList.vue";
import History from "./history.vue";
// import { getAddressByPoints } from "vue-baidu-map-3x"; //baidu-map组件red
// import { useTemplateRefsList } from "@vueuse/core";
import { operatorShowOff ,timeFormat,getYesterday} from "@/utils/common"; // 导入表格api方法生成器
import { useWarnLog } from "@/store/backend/EquipM/warn";
import { useRegion } from "@/store/backend/SysM/region";
import type {
  FormInstance,
  TabsPaneContext,
  FormItemRule,
  FormRules,
} from "element-plus";
// import { ElNotification } from "element-plus"; //处理导航信息
import { useNavTabs } from "@/store/navTabs";
import * as echarts from "echarts/core";
import {
  TitleComponent,
  TitleComponentOption,
  ToolboxComponent,
  ToolboxComponentOption,
  TooltipComponent,
  TooltipComponentOption,
  GridComponent,
  GridComponentOption,
  LegendComponent,
  LegendComponentOption,
  BrushComponent,
  BrushComponentOption,
  MarkAreaComponent,
  MarkAreaComponentOption,
  VisualMapComponent,
  VisualMapComponentOption,
  CalendarComponent,
  CalendarComponentOption,
  DataZoomComponent,
  DataZoomComponentOption
} from "echarts/components";
import {
  LineChart,
  LineSeriesOption,
  ScatterChart,
  ScatterSeriesOption,
  HeatmapChart,
  HeatmapSeriesOption,
} from "echarts/charts";
import { UniversalTransition } from "echarts/features";
import { CanvasRenderer } from "echarts/renderers";
import { keys } from "lodash";
// import baTable from "@/utils/baTable";
// import { baTableApi } from "@/utils/common";
echarts.use([
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  CanvasRenderer,
  UniversalTransition,
  ScatterChart,
  CanvasRenderer,
  UniversalTransition,
  BrushComponent,
  MarkAreaComponent,
  VisualMapComponent,
  HeatmapChart,
  CalendarComponent,
  DataZoomComponent,
]);
type EChartsOption = echarts.ComposeOption<
  | TitleComponentOption
  | ToolboxComponentOption
  | TooltipComponentOption
  | GridComponentOption
  | LegendComponentOption
  | LineSeriesOption
  | BrushComponentOption
  | MarkAreaComponentOption
  | ScatterSeriesOption
  | VisualMapComponentOption
  | HeatmapSeriesOption
  | CalendarComponentOption
  | DataZoomComponentOption
>;
/**
 * 通过坐标获取地址 config和返回值参考百度api
 * @param config {IPointToAddressConfig}  默认值 {extensions_poi 1,output: 'json',coordtype: 'wgs84ll',timeout: 60  }
 * @param aks {String[]} ; ak不传默认使用map ak
 *
 * @return {promise} ;
 */
const config = {
  location: ["31.225696563611", "121.49884033194"],
};

const monitor = useBackendMonitor(); //实时监控仓库
const navTabs = useNavTabs();
const { proxy } = useCurrentInstance(); //mitt
const route = useRoute();
const warnLog = useWarnLog();
const region = useRegion();
const alarm= inject("alarm")as any;


const paneActiveName = ref("monitor"); //外围的tab-pane绑定name，默认显示monitor模块
const activeName = reactive(["1", "2"]); //对接用户的折叠面板绑定name
let historyName = reactive<string[]>([]);

//限制用户只能选择当天之前日期
const pickerOptions = (time: Date) => {
  return time.getTime() > Date.now() - 1 * 24 * 60 * 60 * 1000
}

type Form = {
  location: object;
  address: string;
  model: string;
  remark: string;
};

const check = (rule: any, value: any, callback: any) => { };


interface anyObj {
  [key: string]: any;
}
//基础配置设置
const baseConfig: {
  rules: Partial<Record<string, FormItemRule[]>>; //验证规则
  form: anyObj;
  loading:boolean,
  showForm: boolean;
  calendarLoading:boolean
} = reactive({
  rules: {},
  form: {},
  showForm: false,
  loading:true,
  calendarLoading:false
});

const state: {
  charts: any[];
} = { charts: [] }; //基础折线图
const state2: {
  charts: any[];
} = { charts: [] }; //事件散点图
const state3: {
  charts: any[];
} = { charts: [] }; //坐标热力图
const stateTime = ref("")//折线图获取时间
const defaultTime:{yesterday:string;today:string}=reactive({yesterday:"",today:""})
const historyPart: { show: boolean } = reactive({ show: false })
const deviceEchartRef = ref<HTMLDivElement>(); //获取图表展示的dom 基础数据折现图
const eventEchartsRef = ref<HTMLDivElement>(); //获取图表展示的dom 事件散点图
const historyWorkChartRef = ref<HTMLElement>(); //获取图表展示的dom 坐标热力图
const end=ref(false)//轮询停止
const state4:{type:string}=reactive({type:""})

// //activeName 改变时触发
// const onTabChange = (name: TabPanelName) => {
//   //获取设备的基础信息
//   console.log("name", name);
//   if (name === "history") {
//     historyPart.show = true
//     end.value=true
//   } else {
//     historyPart.show = false
//   }
// };
// 事件列表显示与否
const eventIsShow = ref(false)
// tab 被选中时触发
const onTabClick = (pane: TabsPaneContext, ev: Event) => {
  let tab = pane.props.label;
  switch (tab) {
    case "事件":
      // initEvent();
      eventIsShow.value = true
      break;
    default:
      if (state2.charts.length > 0) {
        state2.charts[0].dispose();
        state2.charts.length = 0;
        eventIsShow.value = false
        monitor.eventDone = false
      }
      break;
  }
};
//当选择项发生变化时会触发该事件
const handleSelectionChange = () => { };

//点击获取该设备的固定天数的综合数据 并展现图表
const showEcharts = (type: string) => {
  state4.type=type
  if (type === "runningTime") {
    if (state3.charts.length > 0) {
      historyName.splice(0); //折叠面板关闭
      state3.charts[0].dispose(); //释放掉echarts
      state3.charts.shift(); //删除数组内的echarts
    } else {
      baseConfig.calendarLoading=true
      historyName.push("1"); //折叠面板打开
      let Query = Object.assign(route.query, stateTime.value !== null ? 
      { params: { 
        beginTime: stateTime.value[0]?stateTime.value[0]:defaultTime.yesterday,
         endTime: stateTime.value[1]?stateTime.value[1]:defaultTime.today} 
        }
          : { params: {} 
        })
      monitor.changeChartOption(type, Query).then((res) => {
        console.log("日历图",res);
        
      baseConfig.calendarLoading=false
        console.log("initEchartsres",res);
        initEcharts(type, res);
      }).catch((err:any)=>{
    baseConfig.calendarLoading=false;
  });
    }
  } else {
    baseConfig.loading=true;
    let Query = Object.assign(route.query, stateTime.value !== null ? 
    { params: { 
      beginTime: stateTime.value[0]?stateTime.value[0]:defaultTime.yesterday,
       endTime: stateTime.value[1]?stateTime.value[1]:defaultTime.today } 
      } 
       : { params: {} 
      })
    state.charts[0].dispose(); //释放掉echarts
    state.charts.shift(); //删除数组内的echarts
    monitor.changeChartOption(type, Query).then(() => {
    baseConfig.loading=false;
      initEcharts(type, {});
    })
    .catch((err:any)=>{
    baseConfig.loading=false;
  });
  }
};

//点击时间默认当前数据项筛选时间
const timeChange=()=>{
  console.log("当前数据项为",state4.type);
  if(state4.type&&state4.type!=='runningTime'){
    showEcharts(state4.type)
  }else{
    if(state4.type==="runningTime"){
    }else{
      let Query = Object.assign(route.query, stateTime.value !== null ? { params: { beginTime: stateTime.value[0], endTime: stateTime.value[1] } } : { params: {} })
      init(Query) 
    }
  }
  
}

//三折线合并图表
const init = (data:any) => {
  baseConfig.loading=true;
  const paramsChart = echarts.init(deviceEchartRef.value as HTMLDivElement);
  let newData=data!==""?data:route.query
  monitor.getNowListObject(newData, "").then((res: any) => {
    baseConfig.loading=false;
    let option: EChartsOption = {
      color: ["#5470c6", "#91cc75", "#ee6666"],
      title: {
        text: "列表",
      },
      tooltip: {
        trigger: "axis",
      },
      legend: {
        data: ["压强", "风速", "温度"],
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "3%",
        containLabel: true,
      },
      toolbox: {
        feature: {
          dataZoom: {
          yAxisIndex: 'none'
      },
      restore: {},
          saveAsImage: {},
        },
      },
      xAxis: {
        type: "category",
        boundaryGap: false,
        data: res[3],
      },
      yAxis: {
        type: "value",
        boundaryGap: [0, '100%']
      },
      dataZoom: [
    {
      type: 'inside',
      start: 0,
      end: 10
    },
    {
      start: 0,
      end: 10
    }
  ],
      series: [
        {
          name: "压强",
          type: "line",
          stack: "Total",
          data: res[0],
        },
        {
          name: "风速",
          type: "line",
          stack: "Total",
          data: res[1],
        },
        {
          name: "温度",
          type: "line",
          stack: "Total",
          data: res[2],
        },
      ],
    };
    paramsChart.setOption(option);
    state.charts.push(paramsChart);
  }).catch((err:any)=>{
    baseConfig.loading=false;
  })

};
//单折线图表+坐标热力图
const initEcharts = (type: string, result: any) => {
  // function getVirtulData(year: string) {
  //   year = year || "2017";
  //   var date = +echarts.number.parseDate(year + "-01-01");
  //   var end = +echarts.number.parseDate(+year + 1 + "-01-01");
  //   var dayTime = 3600 * 24 * 1000;
  //   var data = [];
  //   for (var time = date; time < end; time += dayTime) {
  //     data.push([
  //       echarts.time.format(time, "{yyyy}-{MM}-{dd}", false),
  //       Math.floor(Math.random() * 24),
  //     ]);
  //   }
  //   console.log("getVirtulData",getVirtulData);

  //   return data;
  // }
  const countOption = {
    toolbox: {
      feature: {
        dataView: { readOnly: false },
        restore: {},
        saveAsImage: {},
      },
    },
    tooltip: {
      // position: "top",
      // formatter: function (p: any) {
      //   // 第三个参数 isUTC true表示默认展示UTC时间 false表示默认展示的是本地时间
      //   var format = echarts.time.format(p.data[0], "{yyyy}-{MM}-{dd}", true);
      //   return format + "环保设备总运行时长: " + p.data[1] +"小时";
      // },
    },
    visualMap: {
      min: 0,
      max: 500,
      calculable: true,
      orient: "horizontal", //日历图的布局方向
      left: "center",
      bottom: "15%",
      inRange: {
        color: ["#eeeeee", "#d6e685", "#8cc665", "#44a340", "#1e6723"],
      },
      show: monitor.calendar.visualMapShow,
      seriesIndex: [1],
    },
    legend: [
      // {
      //   name: "更换滤芯",
      //   // 强制设置图形为圆。
      //   icon: "circle",
      // },
    ],
    calendar: [
      {
        orient: monitor.calendar.orient,
        // range: monitor.calendar.range,
        range: new Date().getFullYear(),
        left: "center",
        cellSize: monitor.calendar.cellSize,
        splitLine: {
          show: false,
        },
        //单个日历格子样式
        itemStyle: {
          // color: "#323c48",
          borderWidth: 0,
          // borderColor: "#111",
        },
        dayLabel: {
          firstDay: 1,
          nameMap: "ZH",
        },
        monthLabel: {
          nameMap: "ZH",
        },
        yearLabel: {
          show: false,
        },
      },
    ],
    series: [
      {
        name: "更换滤芯",
        type: "scatter",
        coordinateSystem: "calendar",
        symbolSize: 15,
        calendarIndex: 0,
        itemStyle: {
          color: "orangered",
          shadowBlur: 10,
          shadowOffsetX: 1.5,
          shadowOffsetY: 3,
          shadowColor: "#555",
        },
        data: alarm.carbonChangeList,
        z: 20,
      },
      {
        name:"累计运行时长(小时)",
        type: "heatmap",
        coordinateSystem: "calendar",
        data: result,//日历图数据
        label: {
          show: false,
          formatter: function (params: any) {
            return params.value[1] || "";
          },
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 1,
            shadowColor: "rgba(0, 0, 0, 0.1)",
          },
        },
      },
    ],
  };
  if (type === "runningTime") {
    const historyWorkChart = echarts.init(
      historyWorkChartRef.value as HTMLElement
    );
    historyWorkChart.setOption(countOption);
    state3.charts.push(historyWorkChart);
    historyWorkChart.on("click", function (params) {
      console.log(params);
    });
  } else {
    const paramsChart = echarts.init(deviceEchartRef.value as HTMLElement);
    switch (type) {
      case "flow":
        const optionWindPower = monitor.Option; //从store中获取的经由getters处理过的option
        paramsChart.setOption(optionWindPower);
        state.charts.push(paramsChart);
        break;
      case "temperature":
        const optionTemperature = monitor.Option; //从store中获取的经由getters处理过的option
        paramsChart.setOption(optionTemperature);
        state.charts.push(paramsChart);
        break;
      case "current":
        const optionA = monitor.Option;
        paramsChart.setOption(optionA);
        state.charts.push(paramsChart);
        break;
      case "hz":
        const optionHZ = monitor.Option;
        paramsChart.setOption(optionHZ);
        state.charts.push(paramsChart);
        break;
      case "voltage":
        const optionV = monitor.Option;
        paramsChart.setOption(optionV);
        state.charts.push(paramsChart);
        break;
      default: //从store中获取的经由getters处理过的option
        const optionPa = monitor.Option;
        paramsChart.setOption(optionPa);
        state.charts.push(paramsChart);
        break;
    }
  }
};
//事件散点图
const initEvent = () => {
  const eventEchart = echarts.init(eventEchartsRef.value as HTMLDivElement);
  const hour = [
    "00",
    "01",
    "02",
    "03",
    "04",
    "05",
    "06",
    "07",
    "08",
    "09",
    "10",
    "11",
    "12",
    "13",
    "14",
    "15",
    "16",
    "17",
    "18",
    "19",
    "20",
    "21",
    "22",
    "23",
    "24",
  ];
  const min = [
    "00",
    "01",
    "02",
    "03",
    "04",
    "05",
    "06",
    "07",
    "08",
    "09",
    "10",
    "11",
    "12",
    "13",
    "14",
    "15",
    "16",
    "17",
    "18",
    "19",
    "20",
    "21",
    "22",
    "23",
    "24",
    "25",
    "26",
    "27",
    "28",
    "29",
    "30",
    "31",
    "32",
    "33",
    "34",
    "35",
    "36",
    "37",
    "38",
    "39",
    "40",
    "41",
    "42",
    "43",
    "44",
    "45",
    "46",
    "47",
    "48",
    "49",
    "50",
    "51",
    "52",
    "53",
    "54",
    "55",
    "56",
    "57",
    "58",
    "59",
    "60",
  ];
  let eventOption = {
    title: {
      text: "设备事件概览",
      subtext: "数据来源: 云天工业",
    },
    grid: {
      left: "3%",
      right: "7%",
      bottom: "7%",
      containLabel: true,
    },
    tooltip: {
      axisPointer: {
        show: true,
        type: "cross",
        lineStyle: {
          type: "dashed",
          width: 1,
        },
      },
      showDelay: 0,
      formatter: function (params: any) {
        if (params.value.length > 1) {
          return (
            params.seriesName +
            " :<br/>" +
            params.value[0] +
            " " +
            params.value[1] +
            " "
          );
        } else {
          return (
            params.seriesName +
            " :<br/>" +
            params.name +
            " : " +
            params.value +
            " "
          );
        }
      },
    },
    toolbox: {
      feature: {
        dataZoom: {},
        brush: {
          type: ["rect", "polygon", "clear"],
        },
      },
    },
    brush: {},
    legend: {
      data: [
        // {
        //   name: "开机",
        //   // 强制设置图形为圆。
        //   icon: "triangle",
        // },
        // {
        //   name: "关机",
        //   // 强制设置图形为圆。
        //   icon: "circle",
        // },
        {
          name: "更换滤芯",
          // 强制设置图形为菱形。
          icon: "diamond",
        },
        {
          name: "告警",
          // 强制设置图形为圆。
          icon: "triangle",
        },
      ],
      left: "center",
      bottom: 10,
    },
    xAxis: [
      {
        type: "category",
        boundaryGap: false,
        axisLine: { onZero: false },
        data: time(hour, min),
        show: true,
      },
    ],
    yAxis: [
      {
        type: "category",
        scale: true,
        splitLine: {
          show: false,
        },
      },
    ],
    series: [
      // {
      //   name: "开机",
      //   type: "scatter",
      //   emphasis: {
      //     focus: "series",
      //   },
      //   // prettier-ignore
      //   data: monitor.on,
      //   itemStyle: {
      //     borderColor: "green",
      //     color: "green",
      //   },
      //   markArea: {
      //     silent: true,
      //     itemStyle: {
      //       color: "transparent",
      //       borderWidth: 1,
      //       borderType: "dashed",
      //     },
      //     data: [
      //       [
      //         {
      //           name: "开机",
      //           xAxis: "min",
      //           yAxis: "min",
      //         },
      //         {
      //           xAxis: "max",
      //           yAxis: "max",
      //         },
      //       ],
      //     ],
      //   },
      //   symbol: "triangle",
      // },
      // {
      //   name: "关机",
      //   type: "scatter",
      //   emphasis: {
      //     focus: "series",
      //   },
      //   // prettier-ignore
      //   data: monitor.off,
      //   symbol: "circle",
      //   itemStyle: {
      //     borderColor: "red",
      //     color: "red",
      //   },
      //   markArea: {
      //     silent: true,
      //     itemStyle: {
      //       color: "transparent",
      //       borderWidth: 1,
      //       borderType: "dashed",
      //     },
      //     data: [
      //       [
      //         {
      //           name: "关机",
      //           xAxis: "min",
      //           yAxis: "min",
      //         },
      //         {
      //           xAxis: "max",
      //           yAxis: "max",
      //         },
      //       ],
      //     ],
      //   },
      // },
      {
        name: "更换滤芯",
        type: "scatter",
        emphasis: {
          focus: "series",
        },
        // prettier-ignore
        data: monitor.change,
        symbol: "diamond",
        symbolSize: 20,
        lineStyle: {
          color: "#409eff",
          width: 1,
          type: "dashed",
        },
        itemStyle: {
          borderWidth: 2,
          borderColor: "#409eff",
          color: "#409eff",
        },
        markArea: {
          silent: true,
          itemStyle: {
            color: "transparent",
            borderWidth: 1,
            borderType: "dashed",
          },
          data: [
            [
              {
                name: "更换滤芯",
                xAxis: "min",
                yAxis: "min",
              },
              {
                xAxis: "max",
                yAxis: "max",
              },
            ],
          ],
        },
      },
      {
        name: "告警",
        type: "scatter",
        emphasis: {
          focus: "series",
        },
        // prettier-ignore
        data: warnLog.warn,
        symbol: "triangle",
        symbolSize: 20,
        lineStyle: {
          color: "#5470C6",
          width: 1,
          type: "dashed",
        },
        itemStyle: {
          borderWidth: 2,
          borderColor: "#EE6666",
          color: "yellow",
        },
        markArea: {
          silent: true,
          itemStyle: {
            color: "transparent",
            borderWidth: 1,
            borderType: "dashed",
          },
          data: [
            [
              {
                name: "告警",
                xAxis: "min",
                yAxis: "min",
              },
              {
                xAxis: "max",
                yAxis: "max",
              },
            ],
          ],
        },
      },
    ],
  };
  eventEchart.setOption(eventOption);
  state2.charts.push(eventEchart);
};
const echartsResize = () => {
  //window.innerWidth为屏幕的宽度 在最大宽度为425的小屏设备中修改热力图配置
  nextTick(() => {
    if (state2.charts.length > 0) {
      state2.charts[0].resize();
    }
    if (state3.charts.length > 0) {
      state3.charts[0].resize();
      // 热力图小屏设备 直接竖向展示
      if (window.innerWidth < 425) {
        setTimeout(() => {
          pcHeight.value = "200vh";
          monitor.$patch((state) => {
            state.calendar.cellSize = [32, 22];
            state.calendar.orient = "vertical";
            state.calendar.visualMapShow = false;
          });
        });
      } else {
        pcHeight.value = "100vh";
        monitor.$patch((state) => {
          state.calendar.cellSize = [22, 32];
          state.calendar.orient = "horizontal";
          state.calendar.visualMapShow = true;
        });
      }
    }
    if (state.charts.length > 0) {
      for (const key in state.charts) {
        state.charts[key].resize();
      }
    }
  });
};
const pcHeight = ref("100vh");

onActivated(() => {
  // onActivated生命周期改变图表大小
  echartsResize();
});

//轮询请求接口
const restart=async():Promise<any>=>{
if(end.value){
  return;
}
const response = await monitor.reSatrtGetnowList({ eid: monitor.itemData.eid });
  console.log("response", response);
  monitor.getNowListObject(route.query, "")

  if (response.code !== 200) {
    return response;
  }else{
    await new Promise((resolve) => setTimeout(resolve, 20000));
    return await restart();
  }
}

//获取告警列表
const getWarnEventList=()=>{
  warnLog.getList({
    pageSize:8000,
    regions: region.regionIds + "",
    gatewaycode:  monitor.deviceData.gatewaycode,
              });
}

//获取昨日与现在的时间
const getTimePeriod=()=>{
  let yesterday=timeFormat((new Date).getTime() - 24 * 60 * 60 * 1000,"yyyy-mm-dd")+" 00:00:00"
    let today=timeFormat("","yyyy-mm-dd hh:MM:ss")
    defaultTime.yesterday=yesterday
    defaultTime.today=today
    let Query = Object.assign(route.query, stateTime.value !== null ? { params: { beginTime:yesterday, endTime: today } } : { params: {} })
    //获取活性炭更换事件89
    getAlarmsOfCarbon({ params: { beginTime:yesterday, endTime: today } } )
return Query;
}

onBeforeMount(() => {
  for (const key in state.charts) {
    state.charts[key].dispose();
  }
  if (state2.charts.length > 0) {
    state2.charts[0].dispose();
    state2.charts.length = 0;
    eventIsShow.value = false//事件图表重置
    monitor.eventDone = false//事件列表重置
  }
  window.removeEventListener("resize", echartsResize);
});

//获取活性炭更换事件
const getAlarmsOfCarbon = (query:anyObj) => {
  let filter= Object.assign({ type: "2",gatewaycode:route.query.eid},query)
  alarm.getAlarmsList(filter).then(async (res: any) => {
    console.log("获取活性炭更换事件", res);
    alarm.carbonChangeList = await carbonEvents(res.rows, "runningTime");
  });
};

//遍历出来更换活性炭的数据
const carbonEvents = (data: anyObj, type: string) => {
  let result = [];
  for (let i = 0, len = data.length; i < len; i++) {
    // let YMD = data[i].createTime.split(" ")[0];
    result.push([data[i].eventTime, "更换活性炭"]);
  }
  console.log("resultYMD", result);
  return result;
};

onMounted(() => {
  if (window.innerWidth < 425) {
    pcHeight.value = "1764px";
    setTimeout(() => {
      monitor.$patch((state) => {
        state.calendar.cellSize = [32, 22];
        state.calendar.orient = "vertical";
        state.calendar.visualMapShow = false;
        state.loading = false;
      });
    });
  }
  //默认设置
  setTimeout(() => {
    init(getTimePeriod()); //三折线合并图表 默认前一天至当前时间
    getWarnEventList()
  });
  //待获取数据loading页面转为false
  monitor.$patch((state) => {
    state.loading = false;
  });
  window.addEventListener("resize", echartsResize);
});

setTimeout(() => {
    restart(); 
  },20000);

watch(
  () => monitor.eventDone,
  (newVal, oldVal) => {
    console.log("monitor.eventDone",newVal, oldVal);
    
    if (newVal) {
      console.log("初始化");
      operatorShowOff([route.path + "/edit"])? initEvent():""
    } else {
      if (state2.charts.length > 0) {
        state2.charts[0].dispose();
        state2.charts.length = 0;
        console.log("清空");

      }
    }
  }
);

//离开前 轮询结束
onBeforeUnmount(()=>{
  end.value=true
  warnLog.warn.length=0 //告警事件清空
})
</script>
<style lang="scss" scoped>
.store-tabs {
  width: 100%;

  .monitor-tab-pane {
    .paramsTable {
      height: calc(100vh - 350px);
    }

    .showEchart {
      width: 100%;
      height: calc(100vh - 350px);
    }

    .historyWork {
      width: 100%;
      height: calc(v-bind(pcHeight) - 350px);
    }
  }

  .event-tab-pane {
    .eventEchart {
      width: 100%;
      height: calc(100vh - 350px);
    }
  }

  .basic-tab-pane {
    position: relative;

    .basic-tab-pane-content {
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
      width: 80%;
      width: 80%;

      .map {
        left: 0px;
        top: 0px;
        z-index: 9;
        overflow: hidden;
        width: 600px;
        height: calc(100vh - 600px);
      }
    }
  }
}

.lg-mb-20 {
  margin: 20px 0;
}

// .el-tabs--border-card {
//     border: none;
//     box-shadow: var(--el-box-shadow-light);
//     border-radius: var(--el-border-radius-base);
// }

// .el-tabs--border-card :deep(.el-tabs__header) {
//     background-color: var(--ba-bg-color);
//     border-bottom: none;
//     border-radius: var(--el-border-radius-base);
// }

// .el-tabs--border-card :deep(.el-tabs__item.is-active) {
//     border: 1px solid transparent;
// }

// .el-tabs--border-card :deep(.el-tabs__nav-wrap) {
//     border-radius: var(--el-border-radius-base);
// }

// :deep(.store-tabs) .el-tabs__content {
//     padding: 10px 10px;
//     min-height: 350px;
// }
@media screen and (max-width: 1200px) {
  .lg-mb-20 {
    margin-bottom: 20px;
  }
}
</style>
